package com.hongshu.idle.service.idle.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.GetResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongshu.common.core.constant.NoteConstant;
import com.hongshu.common.core.enums.DealStatusEnum;
import com.hongshu.common.core.enums.PayStatusEnum;
import com.hongshu.common.core.enums.ResponseEnum;
import com.hongshu.common.core.exception.HongshuException;
import com.hongshu.idle.auth.AuthContextHolder;
import com.hongshu.idle.domain.dto.ProductOrderDTO;
import com.hongshu.idle.domain.entity.*;
import com.hongshu.idle.domain.vo.IdleProductOrderVO;
import com.hongshu.idle.domain.vo.IdleProductVO;
import com.hongshu.idle.mapper.idle.*;
import com.hongshu.idle.service.idle.IIdleProductOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品
 *
 * @author: hongshu
 */
@Slf4j
@Service
public class IdleProductOrderServiceImpl extends ServiceImpl<IdleProductOrderMapper, IdleProductOrder> implements IIdleProductOrderService {

    @Autowired
    private IdleUserMapper userMapper;
    @Autowired
    private IdleProductMapper productMapper;
    @Autowired
    private IdleProductOrderMapper orderMapper;
    @Autowired
    private IdlePaymentOrderMapper paymentOrderMapper;
    @Autowired
    private IdlePaymentPayMapper paymentPayMapper;
    @Autowired
    private ElasticsearchClient elasticsearchClient;


    /**
     * 创建订单
     *
     * @param productOrderDTO 订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(ProductOrderDTO productOrderDTO) {
        IdleProductOrder productOrder = new IdleProductOrder();

//        String userId = WebUtils.getRequestHeader(UserConstant.USER_ID);
        String userId = AuthContextHolder.getUserId();
        IdleUser user = userMapper.selectById(userId);
        if (BeanUtil.isEmpty(user)) {
            throw new HongshuException(ResponseEnum.ERROR.getMsg());
        }
        IdleProduct product = productMapper.selectById(productOrderDTO.getProductId());
        if (BeanUtil.isEmpty(product)) {
            throw new HongshuException(ResponseEnum.ERROR.getMsg());
        }
        if (product.getStatus() == 1) {
            throw new HongshuException(ResponseEnum.ERROR.getCode(), "商品已售出");
        }
        if (userId.equals(product.getUid())) {
            throw new HongshuException(ResponseEnum.ERROR.getCode(), "不能购买自己的商品");
        }
        Integer postType = product.getPostType();
        String postMode;
        if (0 == postType) {
            postMode = "物流发货";
        } else {
            postMode = "用户自提";
        }
        if (postMode.equals("物流发货")) {
            productOrder.setPostUsername(productOrderDTO.getUsername());
            productOrder.setPostAddress(productOrderDTO.getAddress());
            productOrder.setPostPhone(productOrderDTO.getPhone());
        } else {
            productOrder.setPostUsername(productOrderDTO.getUsername());
            productOrder.setPostPhone(productOrderDTO.getPhone());
        }
        productOrder.setAnswerBuyMoney(Integer.valueOf(product.getPrice()));

        if (postMode.equals("用户自提")) {
            String selfCode = (int) ((Math.random() * 9 + 1) * 100000) + "";
            productOrder.setPostSelfCode(selfCode);
        }
        // 新增闲宝订单数据
        productOrder.setPostType(postMode);
        productOrder.setOrderNumber(RandomUtil.randomNumbers(12));
        productOrder.setProductId(product.getId());
        productOrder.setProductUid(product.getUid());
        productOrder.setBuyUid(userId);
        productOrder.setProductNum(1);
        productOrder.setProductPostPrice(0L);
        productOrder.setProductPostType(product.getPostType());
        productOrder.setProductMoney(productOrder.getProductNum() * productOrder.getAnswerBuyMoney());
        productOrder.setActualBuyMoney(productOrder.getAnswerBuyMoney());
        productOrder.setOrderStatus(PayStatusEnum.UN_PAY.getCode());
        productOrder.setDealStatus(DealStatusEnum.TEMPORARY.getCode());
        productOrder.setCreateTime(new DateTime());
        productOrder.setUpdateTime(new DateTime());
        orderMapper.insert(productOrder);

        // 更新闲宝商品商品数据
        product.setStatus(1);
        product.setBuyUid(userId);
        product.setUpdateTime(new Date());
        productMapper.updateById(product);
        // 更新ES闲宝数据
        this.updateEsProduct(product.getId(), 1);

        return productOrder.getId();
    }

    /**
     * 更新ES闲宝数据
     */
    private void updateEsProduct(String productId, Integer status) {
        try {
            // Step 1: 获取现有的数据
            GetResponse<IdleProductVO> getResponse = elasticsearchClient.get(g -> g.index(NoteConstant.PRODUCT_INDEX).id(productId), IdleProductVO.class);
            // 检查是否获取到了数据
            if (getResponse.found()) {
                IdleProductVO productSearchVO = getResponse.source();
                // Step 2: 更新 status 字段
                productSearchVO.setStatus(status);
                // Step 3: 将更新后的数据保存回 Elasticsearch
                elasticsearchClient.update(u -> u.index(NoteConstant.PRODUCT_INDEX).id(productId).doc(productSearchVO), IdleProductVO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看订单
     *
     * @param orderNumber 商品订单ID
     */
    @Override
    public Map getOrderDetail(String orderNumber) {
        HashMap<Object, Object> map = new HashMap<>();
        IdleProductOrder productOrder = orderMapper.selectOne(
                new QueryWrapper<IdleProductOrder>().eq("order_number", orderNumber));
        if (BeanUtil.isEmpty(productOrder)) {
            throw new HongshuException(ResponseEnum.ERROR.getMsg());
        }
        map.put("productOrder", productOrder);
        IdleProduct productInfo = productMapper.selectById(productOrder.getProductId());
        map.put("productInfo", productInfo);
        IdlePaymentOrder paymentOrder = paymentOrderMapper.selectById(productOrder.getPaymentOrderId());
        map.put("paymentOrder", paymentOrder);
        IdlePaymentPay paymentPay = paymentPayMapper.selectById(paymentOrder.getPaymentPayId());
        map.put("paymentPay", paymentPay);
        return map;
    }

    /**
     * 订单详情
     *
     * @param productOrderId 商品订单ID
     */
    @Override
    public Object getProductOrderInfo(String productOrderId) {
        IdleProductOrder productOrder = orderMapper.selectById(productOrderId);
        if (BeanUtil.isEmpty(productOrder)) {
            throw new HongshuException(ResponseEnum.ERROR.getMsg());
        }
        return productOrder;
    }

//    @Override
//    public void evaluate(ProductOrderEvaluateDTO evaluateDTO) {
//        productOrderService.lambdaUpdate().eq(IdleProductOrder::getId, evaluateDTO.getId())
//                .eq(IdleProductOrder::getUid, StpUtil.getLoginIdAsString())
//                .eq(IdleProductOrder::getDealStatus, 9)
//                .set(IdleProductOrder::getEvaScore, evaluateDTO.getScore())
//                .set(IdleProductOrder::getEvaContent, evaluateDTO.getContent())
//                .set(IdleProductOrder::getDealStatus, 11)
//                .set(IdleProductOrder::getUpdateTime, new Date()).update();
//    }

    @Override
    public Page<IdleProductOrderVO> getOrdersByUser(long currentPage, long pageSize, String userId, String orderStatus) {
        // 构建查询条件
        QueryWrapper<IdleProductOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buy_uid", userId) // 查询购买者的订单
                .orderByDesc("create_time");

        // 根据订单状态筛选
        // 状态值：0-未支付，1-待支付，2-支付中，3-已支付，4-交易完成
        if (orderStatus != null && !orderStatus.isEmpty()) {
            switch (orderStatus) {
                case "unpaid":
                    queryWrapper.eq("order_status", "0"); // 未支付
                    break;
                case "pending":
                    queryWrapper.eq("order_status", "1"); // 待支付
                    break;
                case "paying":
                    queryWrapper.eq("order_status", "2"); // 支付中
                    break;
                case "paid":
                    queryWrapper.eq("order_status", "3"); // 已支付
                    break;
                case "received":
                    queryWrapper.eq("order_status", "4"); // 交易完成
                case "completed":
                    queryWrapper.eq("order_status", "4"); // 交易完成
                    break;
                case "shipped":
                    queryWrapper.eq("deal_status", "4"); // 待确认
                    break;
                default:
                    // 全部订单，不添加状态条件
                    break;
            }
        }

        // 分页查询订单
        Page<IdleProductOrder> orderPage = orderMapper.selectPage(new Page<>(currentPage, pageSize), queryWrapper);

        // 转换为VO
        Page<IdleProductOrderVO> voPage = new Page<>();
        voPage.setCurrent(orderPage.getCurrent());
        voPage.setSize(orderPage.getSize());
        voPage.setTotal(orderPage.getTotal());
        voPage.setPages(orderPage.getPages());

        // 转换订单数据
        List<IdleProductOrderVO> voList = orderPage.getRecords().stream().map(order -> {
            IdleProductOrderVO vo = new IdleProductOrderVO();
            vo.setId(order.getId())
                    .setOrderNumber(order.getOrderNumber())
                    .setPaymentOrderId(order.getPaymentOrderId())
                    .setProductId(order.getProductId())
                    .setProductUid(order.getProductUid())
                    .setBuyUid(order.getBuyUid())
                    .setProductNum(order.getProductNum())
                    .setProductPostPrice(order.getProductPostPrice())
                    .setProductPostType(order.getProductPostType())
                    .setProductMoney(Long.valueOf(order.getProductMoney()))
                    .setAnswerBuyMoney(Long.valueOf(order.getAnswerBuyMoney()))
                    .setActualBuyMoney(Long.valueOf(order.getActualBuyMoney()))
                    .setOrderStatus(order.getOrderStatus())
                    .setDealStatus(order.getDealStatus())
                    .setPostType(order.getPostType())
                    .setPostSelfCode(order.getPostSelfCode())
                    .setPostUsername(order.getPostUsername())
                    .setPostPhone(order.getPostPhone())
                    .setPostAddress(order.getPostAddress())
                    .setShipUsername(order.getShipUsername())
                    .setShipPhone(order.getShipPhone())
                    .setShipAddress(order.getShipAddress())
                    .setShipNum(order.getShipNum())
                    .setShipCompany(order.getShipCompany())
                    .setShipTime(order.getShipTime())
                    .setRemark(order.getRemark())
                    .setCreateTime(order.getCreateTime())
                    .setUpdateTime(order.getUpdateTime());

            // 设置状态文本
            vo.setOrderStatusText(getOrderStatusText(order.getOrderStatus()));
            vo.setDealStatusText(getDealStatusText(order.getDealStatus()));

            // 查询商品信息
            if (order.getProductId() != null && !order.getProductId().isEmpty()) {
                IdleProduct product = productMapper.selectById(order.getProductId());
                if (product != null) {
                    vo.setProductTitle(product.getTitle())
                            .setProductCover(product.getCover())
                            .setProductDescription(product.getDescription());
                }
            }

            // 查询发布者用户信息
            if (order.getProductUid() != null && !order.getProductUid().isEmpty()) {
                IdleUser productUser = userMapper.selectById(order.getProductUid());
                if (productUser != null) {
                    vo.setProductUsername(productUser.getUsername())
                            .setProductUserAvatar(productUser.getAvatar());
                }
            }

            // 查询购买者用户信息
            if (order.getBuyUid() != null && !order.getBuyUid().isEmpty()) {
                IdleUser buyUser = userMapper.selectById(order.getBuyUid());
                if (buyUser != null) {
                    vo.setBuyUsername(buyUser.getUsername())
                            .setBuyUserAvatar(buyUser.getAvatar());
                }
            }

            return vo;
        }).collect(Collectors.toList());

        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 获取订单状态文本
     * 状态值：0-未支付，1-待支付，2-支付中，3-已支付，4-交易完成
     */
    private String getOrderStatusText(String orderStatus) {
        if (orderStatus == null) return "未知";
        switch (orderStatus) {
            case "0":
                return "未支付";
            case "1":
                return "待支付";
            case "2":
                return "支付中";
            case "3":
                return "已支付";
            case "4":
                return "交易完成";
            default:
                return "未知";
        }
    }

    /**
     * 获取交易状态文本
     */
    private String getDealStatusText(String dealStatus) {
        if (dealStatus == null) return "未知";
        switch (dealStatus) {
            case "pending":
                return "待处理";
            case "processing":
                return "处理中";
            case "completed":
                return "已完成";
            case "cancelled":
                return "已取消";
            default:
                return "未知";
        }
    }
}
